<?php
/**
 * Created by PhpStorm.
 * User: qhzhyt
 * Date: 2018/10/6
 * Time: 15:04
 */

require_once '../conf/conf.php';

if (!isset($_GET['sort'])) {
    $sort = 'time';
} else {
    $sort = $_GET['sort'];
}

if (!isset($_GET['offset'])) {
    $offset = 0;
} else {
    $offset = intval($_GET['offset']);
}

if (!isset($_GET['count'])) {
    $count = 20;
} else {
    $count = intval($_GET['count']);
}

$whereClause = [];

if (isset($_GET['keyword'])) {
    $whereClause['OR'] = [
        'map_name[~]' => $_GET['keyword'],
        'map_id' => intval($_GET['keyword'])
    ];
}

if (isset($_GET['userId'])) {
    $whereClause['user_id'] = $_GET['userId'];
}

$whereClause['LIMIT'] = [$offset, $count];

switch ($sort) {
    case 'time':
        $whereClause['ORDER'] = ['upload_time' => 'DESC'];
        break;
    case 'playCount':
        $whereClause['ORDER'] = ['challenge_count' => 'DESC', 'upload_time' => 'DESC'];
        break;
    case 'collect':
        $whereClause['ORDER'] = ['collect_count' => 'DESC', 'upload_time' => 'DESC'];
        break;
}
session_start();
/*
if (isset($_SESSION['user'])) {
    $user = $_SESSION['user'];
} else {
    $user = ['user_id' => 10000];
}*/
// var_dump($whereClause);

//$whereClause['self_id'] = $user['user_id'];
//$whereClause['collection.map_id']='map.map_id';
#var_dump($whereClause);
$mapList = $db->select('map', '*', $whereClause);

if (isset($_SESSION['user'])) {
    $user = $_SESSION['user'];

    foreach ($mapList as $id => $map) {

        if ($db->get('collection', '*', ['user_id' => $user['user_id'], 'map_id' => $map['map_id']]))
            $mapList[$id]['self_id'] = $user['user_id'];


    }

}

#var_dump($db->log());

echo json_encode(['status' => 1, 'code' => 1, 'size' => count($mapList), 'data' => $mapList]);

// var_dump(['asp'=>999,'ppt'=>'666']);